import sensor, image, time
sensor.reset() # 初始化摄像头
sensor.set_pixformat(sensor.GRAYSCALE) # 设置像素格式为灰度
sensor.set_framesize(sensor.QVGA) # 设置帧大小为QVGA
sensor.skip_frames(time = 2000) # 等待设置生效

# 设置阈值来识别黑色物体
threshold = (0,50) # 较低的阈值可以识别更暗的颜色为黑色

def find_max(blobs):#找最大色块的物体
    max_size=0
    for blob in blobs:
        if blob.pixels() > max_size:
            MAX_blob=blob
            max_size = blob.pixels()
    return MAX_blob

while(True):
    img = sensor.snapshot() # 捕捉图像
    blobs=[
           (0,0,int(img.w()/3),img.h()),#最左边区域
           (int(img.w()/3),0,int(img.w()/3),img.h()),#中间区域
           (int(img.w()*2/3),0,int(img.w()/3),img.h())#最右边区域
           ]
    i=0
    Mblack_size=0#中间黑色区域
    Lblack_size=0#左边黑色区域
    Rblack_size=0#右边黑色区域
    for blob in blobs:
        i=i+1
        if i=1:#最左边的区域
            blackAreas = blob.find_blobs([threshold]) # 查找黑色物体
            max_blob=find_max(blackAreas)
            Lblack_size=max_blob.pixels()
        if i=2:#最中间的区域
            blackAreas = blob.find_blobs([threshold]) # 查找黑色物体
            for blackArea in blackAreas:
                Mblack_size=black_size+blackArea.pixels()
        if i=3:#最右边的区域
            blackAreas = blob.find_blobs([threshold]) # 查找黑色物体
            max_blob=find_max(blackAreas)
            Rblack_size=max_blob.pixels()
    if Mblack_size>=2*(Rblack_size+Lblack_size):
        return blob[2].cx()
    else:
        if Rblack_size>Lblack_size:
            return blob[2]+100
        else:
            return blob[2]-100








